package com.example.nio.message;

import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Data
public class ResponseFuture {

    Logger logger = LoggerFactory.getLogger(getClass());

    private Object object = new Object();

    private String requestId;

    private Request request;

    private Response response;

    private boolean isCompleted = false;

    public ResponseFuture(Request request) {
        this.request = request;
        this.requestId = request.getRequestId();
    }

    /***
     * 获取结果一直会阻塞
     * @return
     */
    public Response getResponse() {
        synchronized (object) {
            if (!isCompleted()) {
                try {
                    object.wait();
                } catch (InterruptedException e) {
                    logger.warn("interrupted while waiting for response");
                }
            }
        }
        return this.response;
    }

    /***
     * 返回结果并解锁
     * @param response
     */
    public void setResponse(Response response) {
        synchronized (object) {
            this.response = response;
            this.isCompleted = true;
            object.notify();
        }
    }
}
